{extend name="layout_container" /}

{block name="main"}

<section style="margin-bottom: 5px;">
    <div class="vue-sku">
        <div v-for="(item, index) in specification" :key="index" class="spec-line">
            <span v-if="!cacheSpecification[index].status">{{ item.name }}</span>
            <el-input size="small" style="width:230px;" v-if="cacheSpecification[index].status"
                      v-model="cacheSpecification[index].name" placeholder="输入产品规格"
                      @keyup.native.enter="saveSpec(index)">
                <el-button slot="append" icon="el-icon-check" type="primary" @click="saveSpec(index)"></el-button>
            </el-input>
            <i class="icon el-icon-edit" v-if="!cacheSpecification[index].status" @click="updateSpec(index)"></i>
            :
            <el-input size="small" style="width:230px;" v-model="addValues[index]" placeholder="多个产品属性以空格隔开"
                      @keyup.native.enter="addSpecTag(index)">
                <el-button slot="append" icon="el-icon-check" type="primary" @click="addSpecTag(index)"></el-button>
            </el-input>
            <el-tag v-for="(tag, j) in item.value" :key="j" closable @close="delSpecTag(index, j)"
                    style="margin-right: 2px;">{{ tag }}
            </el-tag>
            <i class="icon el-icon-circle-close spec-deleted" @click="delSpec(index)"></i>
            <el-divider></el-divider>
        </div>
        <div class="add-spec">
            <el-button size="small" :disabled="specification.length >= 6" @click="addSpec">添加规格属性项目</el-button>
            <el-button size="small" type="primary" @click="save">保存</el-button>
        </div>
    </div>
</section>

<el-alert
        :title="notify"
        description="注意!!增加,删除和修改规格都可能导致商品库存设置失效,请修改后及时处理相关分类下库存"
        type="error">
</el-alert>
{/block}

{block name="style"}
{__block__}
<style>
    .demo-dynamic .el-input {
        width: auto;
    }

    .vue-sku .spec-line {
        position: relative;
    }

    .vue-sku .spec-line .spec-deleted {
        position: absolute;
        right: 0;
        top: 0;
        display: none;
        cursor: pointer;
    }

    .vue-sku .spec-line:hover .spec-deleted {
        display: inline;
    }

</style>
{/block}
{block name='script'}
<script>


    new Vue({
        el: '#app',
        template: "#appCnt",
        data: function () {
            return {
                notify: '{$goodsTotal}个商品,{$goodsStockTotal}个sku涉及此属性设置, 修改后请及时修改sku库存及价格',
                // 规格
                specification: [],
                childProductArray: [],
                // 用来存储要添加的规格属性
                addValues: [],
                cacheSpecification: [] // 缓存规格名称
            }
        },
        computed: {},
        methods: {
            createData() {
                const arr = {$data | raw
            }

                for (let i = 0; i < arr.length; i++) {
                    // 添加数据
                    this.addSpec()
                    // 数据
                    this.specification[i].name = arr[i].name
                    this.specification[i].id = arr[i].id
                    this.addValues[i] = arr[i].value
                    // 缓存按钮键值
                    this.cacheSpecification[i].status = false
                    this.cacheSpecification[i].name = arr[i].name
                    // 构建
                    this.addSpecTag(i)
                }
            },
            // 添加规格项目
            addSpec() {
                if (this.specification.length < 5) {
                    this.cacheSpecification.push({
                        status: true,
                        name: ''
                    })
                    this.specification.push({
                        name: '',
                        value: []
                    })
                }
            },
            // 修改状态
            updateSpec(index) {
                this.cacheSpecification[index].status = true
                this.cacheSpecification[index].name = this.specification[index].name
            },
            // 保存规格名
            saveSpec(index) {
                if (!this.cacheSpecification[index].name.trim()) {
                    this.$message.error('名称不能为空，请注意修改')
                    return
                }
                // 保存需要验证名称是否重复
                if (this.specification[index].name === this.cacheSpecification[index].name) {
                    this.cacheSpecification[index].status = false
                } else {
                    if (this.verifyRepeat(index)) {
                        // 如果有重复的，禁止修改
                        this.$message.error('名称重复，请注意修改')
                    } else {
                        this.specification[index].name = this.cacheSpecification[index].name
                        this.cacheSpecification[index].status = false
                    }
                }
            },
            // 删除规格项目
            delSpec(index) {
                this.specification.splice(index, 1)
                this.handleSpecChange('del')
            },
            verifyRepeat(index) {
                let flag = false
                this.specification.forEach((value, j) => {
                    // 检查除了当前选项以外的值是否和新的值想等，如果相等，则禁止修改
                    if (index !== j) {
                        if (this.specification[j].name === this.cacheSpecification[index].name) {
                            flag = true
                        }
                    }
                })
                return flag
            },
            // 添加规格属性
            addSpecTag(index) {
                let str = this.addValues[index] || ''
                if (!str.trim() || !this.cacheSpecification[index].name.trim()) {
                    this.$message.error('名称不能为空，请注意修改')
                    return
                } // 判空
                str = str.trim()
                let arr = str.split(/\s+/) // 使用空格分割成数组
                let newArr = this.specification[index].value.concat(arr)
                newArr = Array.from(new Set(newArr)) // 去重
                this.$set(this.specification[index], 'value', newArr)
                this.clearAddValues(index)
                this.handleSpecChange('add')
                this.specification[index].name = this.cacheSpecification[index].name
                this.cacheSpecification[index].status = false
            },
            // 删除规格属性
            delSpecTag(index, num) {
                this.specification[index].value.splice(num, 1)
                this.handleSpecChange('del')
            },
            // 清空 addValues
            clearAddValues(index) {
                this.$set(this.addValues, index, '')
            },
            /**
             * [handleSpecChange 监听标签的变化,当添加标签时；求出每一行的hash id，再动态变更库存信息；当删除标签时，先清空已有库存信息，然后将原有库存信息暂存到stockCopy中，方便后面调用]
             * @param  {[string]} option ['add'|'del' 操作类型，添加或删除]
             * @return {[type]}        [description]
             */
            handleSpecChange(option) {
                const stockCopy = JSON.parse(JSON.stringify(this.childProductArray))
                if (option === 'del') {
                    this.childProductArray = []
                }
            },
            /*
                计算属性的乘积
                @params
                  specIndex 规格项目在 advancedSpecification 中的序号
              */
            countSum(specIndex) {
                let num = 1
                this.specification.forEach((item, index) => {
                    if (index >= specIndex && item.value.length) {
                        num *= item.value.length
                    }
                })
                return num
            },
            save() {
                let _this = this
                _this.$confirm(
                    this.notify,
                    '确定保存?',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                    $.post('{$urlSave}', {attr: this.specification}, function (rs) {
                        if (rs.code === 200) {
                            _this.$message.success({
                                type: 'success',
                                message: rs.msg,
                                duration: 800,
                                onClose: function () {
                                    window.location.reload()
                                }
                            });
                        } else {
                            _this.error(rs.msg);
                        }
                    }, 'json')
                })
            }
        },
        created: function () {
            this.createData()
        }
    })
</script>
{/block}